﻿using System;
using System.Collections.Generic;
using Autofac;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Lonewolf.WebApp.Controllers;
using Lonewolf.IService;
using Lonewolf.Service;
using Lonewolf.Entity;
using Autofac.Extensions.DependencyInjection;

namespace Lonewolf.WebApp
{
    /// <summary>
    /// IOC注入容器
    /// </summary>
    public class AutoFacConfig : Autofac.Module
    {
        /// <summary>
        /// IOC容器
        /// </summary>
        public static IContainer Container { get; set; }
        
        /// <summary>
        /// 获取组件
        /// </summary>
        /// <typeparam name="T">组件类型</typeparam>
        /// <returns></returns>
        public static T Resolve<T>()
        {
            try
            {
                if (Container == null)
                {
                    Container = Startup.ApplicationContainer;
                    return Container.Resolve<T>();
                }
                else
                {
                    return Container.Resolve<T>();
                }
                //return default(T);
            }
            catch (Exception ex)
            {

                throw new Exception("IOC实例化出错。" + ex.Message);
            }
        }

        protected override void Load(ContainerBuilder builder)
        {
            //service
            Assembly bllAss = Assembly.Load("Lonewolf.Service");
            Type[] bllTypes = bllAss.GetTypes();
            builder.RegisterTypes(bllTypes).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
            //builder.RegisterTypes(bllTypes).Where(a => a.Name.EndsWith("UnitOfWork")).AsImplementedInterfaces();
            //属性注入泛注册
            Assembly ControllerAss = Assembly.Load("Lonewolf.WebApp");
            Type[] ControllerTypes = ControllerAss.GetTypes();
            builder.RegisterTypes(ControllerTypes).Where(a => a.Name.EndsWith("Controller")).PropertiesAutowired();
            //注册工作单元
            //builder.RegisterType(typeof(IUnitOfWork)).As(typeof(UnitOfWork<EFDbContext>));
            //Container = Startup.ApplicationContainer;
            //serviceProvider = new AutofacServiceProvider(Container);
            //DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
            //在无法使用构造函数注入时候可以使用以下方法注册使用
            //var wxList = AutoFacConfig.Resolve<IxxxService>().xxx();

        }

    }
}
